$(function () {
    var timer = null;

    getShopData();

    $('#shopCart')
        .on('tap', '.reduce', reduceEvent)
        .on('tap', '.add', addEvent)
        .on('keyup', '.num', numChangeEvent)
        .on('blur', '.num', numBlurEvent)
        .on("change", ".check", setTotal);

    $("#checkAll").change(checkAllFn);

    $("#confirmOrder").tap(confirmOrderFn);

    function confirmOrderFn() {
        $("input[type=checkbox]").each(function () {
            if ($(this).prop("checked") == true) {
                var id = $(this).parents("li").attr("data-id");
                var option = {
                    type: 'post',
                    url: Api.shopCartUrl,
                    data: {
                        postType: 'submit',
                        id: id
                    }
                };
                requestEvent(option).then(function (res) {
                    console.log(res);
                });
            }
        })
        window.location.href = "confirm_order.html";
    }

    function checkAllFn() {
        $(".check").prop('checked', $(this).prop('checked'));
        setTotal();
    }

    function numBlurEvent() {
        var _this = $(this);
        var num = _this.val();
        var id = _this.parents('li').attr('data-id');
        if (!num) {
            $(this).val(1);
        }
        changeNum(id, num);
    }

    function numChangeEvent() {
        var _this = $(this);
        var num = _this.val();
        num = num.replace(/[^\d]+/, '').replace(/^0+/, '');
        _this.val(num);
    }

    function changeNum(id, num) {
        if (timer) {
            window.clearTimeout(timer);
        }
        timer = setTimeout(function () {
            var option = {
                type: 'post',
                url: Api.shopCartUrl,
                data: {
                    postType: 'changeNum',
                    id: id,
                    num: num,
                }
            };
            requestEvent(option).then(function (res) {
                console.log(res);
            })
        }, 300);
    }

    function setTotal() {
        var total = 0;
        $('#shopCart .check').each(function () {
            var _this = $(this);
            if (_this.prop("checked")) {
                var num = _this.parents("li").find('input[name=amount]').val();
                var price = _this.parents("li").find('.price em').text();
                total += num * price;
            }
        });
        total = total.toFixed(2);
        $('#totalPrice').text(total);
        isCheckAll();
    }

    function isCheckAll() {
        var isAll = $('#shopCart .check').length === $('#shopCart .check:checked').length;
        $("#checkAll").prop("checked", isAll);
    }

    function addEvent() {
        var _this = $(this);
        var eleNum = _this.prev();
        var id = _this.parents('li').attr('data-id');
        var num = eleNum.val();
        num++;
        eleNum.val(num);
        setTotal()
    }

    function reduceEvent() {
        var _this = $(this);
        var eleNum = _this.next();
        var id = _this.parents('li').attr('data-id');
        var num = eleNum.val();
        if (num > 1) {
            num--;
            eleNum.val(num);
            setTotal();
            changeNum(id, num);
        }
    }

    function createHtml(data) {
        var str = '';
        data.forEach(function (item) {
            str += '<li data-id="' + item.shopcart_id + '">'
                + '<input class="check" type="checkbox">'
                + '<img src="' + item.img_src + '" alt="shopcart1">'
                + '<span class="title">' + item.title + '</span>'
                + '<span class="price">￥<em>' + item.price + '</em></span>'
                + '<div class="amount">'
                + '<i class="reduce">-</i>'
                + '<input class="num" type="text" value="' + item.num + '" name="amount">'
                + '<i class="add">+</i>'
                + '</div>'
                + '</li>';
        });
        $('#shopCart').html(str);
        setTotal();
        isCheckAll()
    }

    function getShopData() {
        var option = {
            url: Api.shopCartUrl,
            data: {
                getType: 'getShopcart',
            }
        }
        requestEvent(option).then(createHtml)
    }
});
